import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import BackendService

ApplicationWindow {
    id: loginWindow
    width: 400
    height: 320
    visible: true
    title: "Login"
    flags: Qt.FramelessWindowHint | Qt.Window | Qt.Tool
    color: "transparent"
    
    // 登录状态
    property bool isLoggedIn: false
    
    // 自动登录状态
    property bool autoLogin: false
    
    
    // 使用全局的后端服务实例
    Component.onCompleted: {
        console.log("Login.qml 组件初始化完成，读取保存的登录信息");
        
        // 从设置文件读取自动登录状态
        autoLogin = backendService.loadAutoLogin();

        // 连接全局commandExecutor的信号
        commandExecutor.loginResult.connect(handleLoginResult);
    }
    
    // 打开服务器地址设置窗口
    function openServerHostSetting() {
        var component = Qt.createComponent("ServerHostSetting.qml");
        if (component.status === Component.Ready) {
            var settingWindow = component.createObject(loginWindow);
            if (settingWindow) {
                // 设置窗口位置（在登录窗口中央）
                settingWindow.x = loginWindow.x + (loginWindow.width - settingWindow.width) / 2;
                settingWindow.y = loginWindow.y + (loginWindow.height - settingWindow.height) / 2;
                settingWindow.show();
            }
        } else {
            console.log("创建服务器地址设置窗口失败:", component.errorString());
        }
    }
    
    function handleLoginResult(resultCode, message, domains) {
        console.log("登录结果 - 代码:", resultCode, "消息:", message, "域名数量:", domains.length);
        
        // 检查resultCode
        if (resultCode === 0) {
            // 登录成功，跳转到Main.qml
            console.log("登录成功，域名列表:", domains);
            isLoggedIn = true;
            
            // 创建并显示主窗口
            var mainWindowComponent = Qt.createComponent("Main.qml");
            if (mainWindowComponent.status === Component.Ready) {
                var mainWindow = mainWindowComponent.createObject();
                mainWindow.show();
                loginWindow.close();
                console.log("成功跳转到Main.qml");
            } else {
                console.log("创建主窗口失败:", mainWindowComponent.errorString());
            }
        } else {
            // 登录失败
            console.log("登录失败，错误代码:", resultCode, "错误消息:", message);
            // TODO: 可以在这里显示错误消息给用户
        }
    }
    
    // 登录容器
    Rectangle {
        id: loginContainer
        anchors.fill: parent
        color: "#ffffff"
        radius: 8
        border.color: "#d0d0d0"
        border.width: 1
        clip: true
        
        // 窗口拖拽区域
        MouseArea {
            anchors.fill: parent
            property point startMousePos
            property point startWindowPos
            
            onPressed: {
                startMousePos = Qt.point(mouseX, mouseY);
                startWindowPos = Qt.point(loginWindow.x, loginWindow.y);
            }
            
            onPositionChanged: {
                if (pressed) {
                    var deltaX = mouseX - startMousePos.x;
                    var deltaY = mouseY - startMousePos.y;
                    loginWindow.x = startWindowPos.x + deltaX;
                    loginWindow.y = startWindowPos.y + deltaY;
                }
            }
        }
        
        // 窗口工具栏
        WindowToolBar {
            id: loginToolBar
            anchors.top: parent.top
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.margins: 1
            mainWindow: loginWindow
        }
        
        ColumnLayout {
            anchors.top: loginToolBar.bottom
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.bottom: parent.bottom
            anchors.margins: 30
            spacing: 20
            
            // 标题
            Text {
                text: "用户登录"
                font.pixelSize: 24
                font.bold: true
                color: "#333333"
                Layout.alignment: Qt.AlignHCenter
            }
            
            // 用户名输入框
            ColumnLayout {
                Layout.fillWidth: true
                spacing: 5
                
                // Text {
                //     text: "用户名"
                //     font.pixelSize: 14
                //     color: "#666666"
                // }
                
                TextField {
                    id: usernameField
                    // text: "admin1"
                    Layout.fillWidth: true
                    // Layout.preferredHeight: 40
                    placeholderText: "请输入用户名"                    
                    font.pixelSize: 14
                    leftPadding: 8
                    rightPadding: 8
                    topPadding: 8
                    bottomPadding: 8
                    background: Rectangle {
                        color: "transparent"
                        border.color: "#d0d0d0"
                        border.width: 1
                        radius: 5
                    }
                    MouseArea {
                        anchors.fill: parent
                        propagateComposedEvents: true
                        onPressed: mouse.accepted = false
                    }
                }
            }
            
            // 密码输入框
            ColumnLayout {
                Layout.fillWidth: true
                spacing: 5
                
                // Text {
                //     text: "密码"
                //     font.pixelSize: 14
                //     color: "#666666"
                // }
                
                TextField {
                    id: passwordField
                    // text: "123456"
                    Layout.fillWidth: true
                    // Layout.preferredHeight: 40
                    placeholderText: "请输入密码"
                    echoMode: TextInput.Password
                    font.pixelSize: 14
                    leftPadding: 8
                    rightPadding: 8
                    topPadding: 8
                    bottomPadding: 8
                    background: Rectangle {
                        color: "transparent"
                        border.color: "#d0d0d0"
                        border.width: 1
                        radius: 5
                    }
                    MouseArea {
                        anchors.fill: parent
                        propagateComposedEvents: true
                        onPressed: mouse.accepted = false
                    }
                }
            }
            
            // 登录按钮
            Button {
                Layout.fillWidth: true
                Layout.preferredHeight: 40
                text: "登录"
                font.pixelSize: 16
                font.bold: true
                background: Rectangle {
                    color: parent.pressed ? "#1976d2" : "#2196f3"
                    radius: 4
                }
                contentItem: Text {
                    text: parent.text
                    font: parent.font
                    color: "#ffffff"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
                onClicked: {
                    // 验证输入
                    if (usernameField.text.trim() !== "" && passwordField.text.trim() !== "") {
                        console.log("开始登录，用户名:", usernameField.text);
                        // 通过 CommandExecutor 进行登录
                        commandExecutor.executeLoginCheckin(usernameField.text.trim(), passwordField.text.trim(), "1234");
                    } else {
                        console.log("请输入用户名和密码");
                    }
                }
            }
            
            // 自动登录选项和设置按钮
            RowLayout {
                Layout.fillWidth: true
                
                CheckBox {
                    id: autoLoginCheckBox
                    text: "自动登录"
                    font.pixelSize: 12
                    checked: autoLogin
                    indicator: Rectangle {
                        implicitWidth: 16
                        implicitHeight: 16
                        x: parent.leftPadding
                        y: parent.height / 2 - height / 2
                        radius: 3
                        border.color: parent.checked ? "#2196f3" : "#d0d0d0"
                        border.width: 1
                        color: parent.checked ? "#2196f3" : "transparent"
                        
                        Text {
                            anchors.centerIn: parent
                            text: "✓"
                            color: "#ffffff"
                            font.pixelSize: 10
                            visible: parent.parent.checked
                        }
                    }
                    contentItem: Text {
                        text: parent.text
                        font: parent.font
                        color: "#666666"
                        verticalAlignment: Text.AlignVCenter
                        leftPadding: parent.indicator.width + parent.spacing
                    }
                    
                    onCheckedChanged: {
                        autoLogin = checked;
                        console.log("自动登录状态改变:", checked);
                        // 保存自动登录状态到设置文件
                        backendService.saveAutoLogin(checked);
                    }
                }
                
                Item {
                    Layout.fillWidth: true
                }
                
                // 设置按钮
                Rectangle {
                    width: 32
                    height: 32
                    color: settingsMouseArea.containsMouse ? "#e0e0e0" : "transparent"
                    radius: 4
                    
                    Text {
                        anchors.centerIn: parent
                        text: "⚙"
                        font.pixelSize: 16
                        color: "#333333"
                    }
                    
                    MouseArea {
                        id: settingsMouseArea
                        anchors.fill: parent
                        hoverEnabled: true
                        onClicked: {
                            openServerHostSetting();
                        }
                    }
                }
            }
            
            Item {
                Layout.fillHeight: true
            }
        }
    }
}
